﻿using System.Web.Security;
using System;
namespace Alphadon.TimeStream.Services.Membership
{
    public class MembershipServices : IMembershipService
    {
        public readonly MembershipProvider _provider;

        public MembershipServices() : this(null) { }

        public MembershipServices(MembershipProvider provider)
        {
            _provider = provider ?? System.Web.Security.Membership.Provider;
        }

        public int MinPasswordLength
        {
            get { return _provider.MinRequiredPasswordLength; }
        }

        public bool ValidateUser(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName)) throw new ArgumentException("Username cannot be null", "userName");
            if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be null", "password");
            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email)
        {
            if (string.IsNullOrEmpty(userName)) throw new ArgumentException("Username cannot be null", "userName");
            if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password cannot be null", "password");
            if (string.IsNullOrEmpty(email)) throw new ArgumentException("Email cannot be null", "email");
            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, null, null, true, null, out status);
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            if (string.IsNullOrEmpty(userName)) throw new ArgumentException("Username cannot be null", "userName");
            if (string.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Old Password cannot be null", "oldPassword");
            if (string.IsNullOrEmpty(newPassword)) throw new ArgumentException("New Password cannot be null", "newPassword");
            try
            {
                MembershipUser currentUser = _provider.GetUser(userName, true);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }
    }
}
